package com.itheima.service.Impl;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import com.itheima.util.Page;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.*;

public class BrandServiceImpl implements BrandService {
    SqlSessionFactory sql = SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public Page getall(int dqys, int myts) {
        SqlSession sqlSession = sql.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        Page page = new Page();
        page.setPageCount(mapper.Count());
        List<Brand> getall = mapper.getall((dqys - 1) * myts, myts);
        page.setBrands(getall);
        sqlSession.close();
        return page;
    }

    @Override
    public void ins(Brand brand) {
        SqlSession sqlSession = sql.openSession(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.add(brand);
        sqlSession.close();
    }

    @Override
    public void deleteByIds(Integer[] ids) {
        SqlSession sqlSession = sql.openSession(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.deleteByIds(ids);
        sqlSession.close();
    }

    @Override
    public Page getallAnd(int dqys, int myts, Brand brand) {
        SqlSession sqlSession = sql.openSession(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        String companyName = brand.getCompanyName();
        String brandName = brand.getBrandName();
        if (companyName != null || "".equals(companyName)) {
            brand.setCompanyName("%"+companyName+"%");
        }
        if (brandName != null || "".equals(brandName)) {
            brand.setBrandName("%"+brandName+"%");
        }
        Page page = new Page();
        page.setPageCount(mapper.Countand(brand));
        List<Brand> getalland = mapper.getalland((dqys - 1) * myts, myts, brand);
        page.setBrands(getalland);
        sqlSession.close();
        return page;
    }



    @Override
    public void updBrand(Brand brand) {
        SqlSession sqlSession = sql.openSession(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.updBrand(brand);
        sqlSession.close();
    }


}
